
from zope.interface import implements
from zope.viewlet.interfaces import IViewlet

from Acquisition import aq_base, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.Five.browser import BrowserView

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile

from plone.app.layout.viewlets.common import ViewletBase
from plone.app.layout.viewlets.comments import CommentsViewlet

from Products.CMFPlone import PloneMessageFactory as _


class APKNFooterViewlet(ViewletBase):
	render = ViewPageTemplateFile('templates/footer.pt')
	

class LogoViewlet(ViewletBase):
	'''
	Customized logo viewlet for APKN
	to allow display of the Logos
	for different sections and/or
	different languages
	'''
	index = ViewPageTemplateFile('templates/logo.pt')

	def update(self):
		super(LogoViewlet, self).update()

		portal = self.portal_state.portal()
		logoName = portal.restrictedTraverse('base_properties').logoName
		self.logo_tag = portal.restrictedTraverse(logoName).tag()
		self.portal_title = self.portal_state.portal_title()
		self.the_language = self.request['LANGUAGE']
		self.the_request = self.request
		self.logo_text = _(u'logo_alt_text', default=u'Home')
		if(self.the_language is ''):
			self.the_language = 'en'

class LanguageSelector(BrowserView):
	"""Language selector customizations"""
	implements(IViewlet)

	render = ZopeTwoPageTemplateFile('templates/languageselector.pt')

	def __init__(self, context, request, view, manager):
		super(LanguageSelector, self).__init__(context, request)
		self.__parent__ = view
		self.context = context
		self.request = request
		self.view = view
		self.manager = manager
		self.tool = getToolByName(context, 'portal_languages', None)
		portal_tool = getToolByName(context, 'portal_url', None)
		self.portal_url = None
		if portal_tool is not None:
			self.portal_url = portal_tool.getPortalObject().absolute_url()

	def update(self):
		pass

	def no_translation(self, code):
		if hasattr(self.context, 'hasTranslation'):
			return not self.context.hasTranslation(code)
		else:
			#cannot determine
			return False
	
	def available(self):
		if self.tool is not None:
			# Ask the language tool. Using getattr here for BBB with older
			# versions of the tool.
			showSelector = getattr(aq_base(self.tool), 'showSelector', None)
			if showSelector is not None:
				return self.tool.showSelector() # Call with aq context
			# BBB
			return bool(self.tool.use_cookie_negotiation)
		return False

	def languages(self):
		"""Returns list of languages."""
		if self.tool is None:
			return []

		bound = self.tool.getLanguageBindings()
		current = bound[0]

		def merge(lang, info):
			info["code"]=lang
			if lang == current:
				info['selected'] = True
			else:
				info['selected'] = False
			return info

		languages = [merge(lang, info) for (lang,info) in
						self.tool.getAvailableLanguageInformation().items()
						if info["selected"]]
		
		# sort supported languages by index in portal_languages tool
		supported_langs = self.tool.getSupportedLanguages()
		def index(info):
			try:
				return supported_langs.index(info["code"])
			except ValueError:
				return len(supported_langs)
		
		return sorted(languages, key=index) 

	def showFlags(self):
		"""Do we use flags?."""
		if self.tool is not None:
			return self.tool.showFlags()
		return False


class APKNCommentsViewlet(CommentsViewlet):
	'''
	Restores comment viewlets behaviour within other Plone sites
	removing Cynin customizations
	This is also a good place to set up any desired customizations
	'''
	render = ViewPageTemplateFile("templates/comments.pt")
